<?php
        	
namespace Addons\BLConn\Model;
use Home\Model\WeixinModel;

/**
 * BLConn的微信模型
 */
class WeixinAddonModel extends WeixinModel{
	function reply($dataArr, $keywordArr = array()) {
		$config = getAddonConfig ( 'BLConn' ); // 获取后台插件的配置参数	
		//dump($config);

	} 

	// 关注公众号事件
	public function subscribe($data) {
		//获取推荐人ID
		$referrerId = 0;
		if(preg_match('/^qrscene_/', $data['EventKey'])) {
			$referrerId = preg_replace('/^qrscene_/', '', $data['EventKey']);
			$referrerId = intval($referrerId);
		}
		$this->register($referrerId);

		return true;
	}
	
	// 取消关注公众号事件
	public function unsubscribe() {
		return true;
	}
	
	// 扫描带参数二维码事件
	public function scan($data) {
		//获取推荐人ID
		$referrerId = 0;
		if(!empty($data['EventKey'])) {
			$referrerId = intval($data['EventKey']);
		}
		$this->register($referrerId);

		return true;
	}
	
	// 上报地理位置事件
	public function location() {
		return true;
	}
	
	// 自定义菜单事件
	public function click() {
		return true;
	}

	//注册用户
	private function register($referrerId = 0) {
		$userModel = M('user');
		$openId = get_openid();
		$token = get_token();

		//判断用户是否已注册
		$isRegister = $userModel->where("token='$token' and openId='$openId'")->count();
		if(!$isRegister) {
			//获取注册者微信资料
			$wxUserInfo = getWeixinUserInfo($openId, $token);

			//获取推荐者信息
			if(!empty($referrerId)) {
				$referrerData = $userModel->where("id=$referrerId")->find();
				empty($referrerData) && $referrerId = 0;
			}

			//入库
			$userData['nickname'] = $wxUserInfo['nickname'];
			$userData['image'] = $wxUserInfo['headimgurl'];
			$userData['sex'] = $wxUserInfo['sex'];
			$userData['referrerId'] = $referrerId;
			$userData['score'] = 0;
			$userData['integralTank'] = 0;
			$userData['registerTime'] = time();
			$userData['openId'] = $openId;
			$userData['token'] = $token;
			checkUserId();
			$result = $userModel->add($userData);

			if($result) {
				$config = getAddonConfig('BLCConfig');
				if(!empty($config['referrerScore']) && !empty($referrerId)) {
					$userModel->where("id=$referrerId")->setInc('integralTank', $config['referrerScore']);
					//判断会员是否已经达到积分罐上限
					checkIntegralTank($referrerId);
				}

				//微信文本消息提示注册成功
				if(!empty($referrerData)) {
					$content = "欢迎您【{$userData['nickname']}】，您由【{$referrerData['nickname']}】推荐关注纤仙联盟！^_^";
					send_custom_info($referrerData['openId'], "您推荐了【{$userData['nickname']}】关注纤仙联盟！^_^");	//通知推荐者
				} else {
					$content = "欢迎您【{$userData['nickname']}】，恭喜您加入纤仙联盟！^_^";
				}
				$this->replyText($content);	//通知注册者

				return true;
			}
		}
		return false;
	}
}
        	